<template>
  <div>
    <el-dialog
      :title="title"
      width="652px"
      :visible.sync="isShow"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="140px" :rules="rules">
        <el-form-item label="企业名称" prop="tenantName">
          <el-autocomplete
            style="width: 280px"
            v-model="form.tenantName"
            :fetch-suggestions="querySearch"
            placeholder="请输入企业名称"
            :trigger-on-focus="false"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="企业统一信用代码" prop="uscCode">
          <el-input v-model="form.uscCode" disabled placeholder="请填写企业统一信用代码"></el-input>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input v-model="form.discount" placeholder="请填写折扣"><template slot="append">%</template></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="type">
          <el-switch v-model="form.type"> </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { isInteger } from '@/utils/validator.js'
export default {
  name: 'ImportPop',
  components: {},
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    popData: {
      type: Object,
      default: () => {
        return
      },
    },
    itemData: {
      type: String,
      default: '',
    },
    updateFormSubmit: {
      type: Function,
      default: () => {
        return
      },
    },
  },
  data() {
    const checkAccountNumber = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error('只能输入数字'))
      } else if (Number(value) > 100 || Number(value) < 0) {
        callback(new Error('产品折扣不能大于100且小于0'))
      } else {
        callback()
      }
    }
    return {
      btnText: '确定',
      rules: {
        discount: [{ required: true, message: '请输入产品折扣' }, { validator: checkAccountNumber }],
      },
      form: {
        id: '',
        discount: '0',
        productCode: '',
        type: true,
        fundCode: '',
        uscCode: '',
        tenantName: '',
      },
      sourceList: [],
      productList: [],
      options: [],
    }
  },
  computed: {},
  methods: {
    handleClose() {
      console.log('1111')
      this.resetData()
      this.$emit('update:isShow', !this.isShow)
    },
    resetData() {
      this.form.discount = '0'
      this.form.productCode = ''
      this.form.type = true
      this.form.fundCode = ''
      this.form.uscCode = ''
      this.form.tenantName = ''
      this.$refs['form'].resetFields()
    },
    changeSource(val) {
      this.getProductRequest(val)
    },
    uploadSuccess(res, file) {
      this.form.fileUrl = res.data
      this.form.fileName = file.name
      this.$refs.form.validateField('fileUrl')
    },
    submit() {
      this.$refs['form'].validate(async valid => {
        if (!valid) return
        await this.saveRequest()
      })
    },
    async saveRequest() {
      const obj = {
        discount: this.form.discount,
        productCode: this.popData.productCode,
        fundCode: this.popData.fundCode,
        type: this.form.type ? 1 : 2, //折扣状态 1启用 2禁用 ,
        uscCode: this.form.uscCode,
      }
      // 折扣状态 1启用 2禁用 ,
      await this.$http.post('/products/addDiscont', obj)
      this.$message.success('更新成功')
      this.$emit('update:isShow', !this.isShow)
      this.$emit('updateFormSubmit')
    },
    async getSourceRequest() {
      const res = await this.$http.get('/app/list')
      this.sourceList = res || []
    },
    async getProductRequest(appCodes) {
      const res = await this.$http.get('/products/list', {
        params: {
          appCodes: appCodes.toString(),
        },
      })
      this.productList = res
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    async querySearch(queryString, cb) {
      this.form.uscCode = ''
      let corpList = this.corpList
      const nameval = queryString.toString()
      const obj = {
        coreName: nameval,
        appCode: this.popData.appCode,
      }
      const res = await this.$http.post('/products/queryCorp', obj)
      console.log('res==', res)

      corpList = res || []
      let results = queryString ? corpList.filter(this.createFilter(queryString)) : corpList
      for (let i = 0; i < results.length; i++) {
        results[i].value = results[i].tenantName
      }
      // this.form.uscCode =
      // this.form.type  = id;
      // 调用 callback 返回建议列表的数据
      cb(results)
      //   }
      // });
    },
    //反选
    async selectPjmtBank() {
      this.corpList = []
      const obj = {
        coreName: '',
        appCode: this.popData.appCode,
      }
      const res = await this.$http.post('/products/queryCorp', obj)
      this.corpList = res || []
      for (let i = 0; i < this.corpList.length; i++) {
        this.corpList[i].value = this.corpList[i].tenantName
      }
      console.log('listdata==', this.corpList)
    },
    handleSelect(data) {
      console.log('data==', data)
      this.form.uscCode = data.uscCode || ''
    },
    createFilter(queryString) {
      return item => {
        return item.tenantName.indexOf(queryString) >= 0
      }
    },
  },
  mounted() {
    console.log('popData==', this.popData)
    if (this.title === '编辑') {
      this.form = { ...this.itemData }
      console.log('data==', this.form)
    }
    this.getSourceRequest()
    this.popData.appCode && this.selectPjmtBank()
  },
  watch: {
    title(newName, oldName) {
      console.log('newName==', newName)
      if (newName === '编辑') {
        const obj = JSON.parse(this.itemData)
        this.form = { ...obj }
        this.form.tenantName = obj.corpName
        this.form.type = this.form.type === 2 ? false : true
        console.log('this.form ', this.form)
      } else {
        this.form = {
          id: '',
          discount: '0',
          type: true, //折扣状态 1启用 2禁用 ,
          uscCode: '',
          productCode: '',
        }
      }
    },
    'form.tenantName'(newVal, oldVal) {
      if (!newVal) {
        this.form.uscCode = ''
      }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-input {
    width: 400px;
  }
  .el-input__inner {
    width: 400px;
  }
  .el-textarea {
    width: 400px;
  }
}
.btn {
  width: 400px;
}
</style>
